<template>
  <q-dialog v-model="visible" :persistent="!state">
    <q-card
      :class="ui.cardClass"
      style="
        max-width: 95vw;
        max-height: calc(100vh - 2rem);
        overflow-x: hidden;
      "
    >
      <modify-storage-posture
        ref="modifyPostures"
        modify
        @remove="removePosture"
      />
      <modify-storage-posture ref="newStoragePosture" @remove="removePosture" />
      <q-card-section class="flex items-center q-gutter-x-sm bg-indigo">
        <div class="text-h6 text-white">
          {{
            (state ? $t(lang + "添加") : $t(lang + "修改")) +
            (norm.onRobot ? $t(lang + "自生库") : $t(lang + "库位"))
          }}
        </div>
        <!--        <photo-dialog  v-if="mode==='device'" label="查看当前相机" color="primary"/>-->
        <q-space />
        <!--        <q-toggle label="自身标定" v-model="norm.onRobot" class="q-mr-md" v-if="state&&optionsIndex.length!==0"/>-->
        <q-btn
          no-caps
          color="primary"
          icon="add_a_photo"
          :label="$t(lang + '获取校准坐标')"
          @click="creatorCord"
        />
        <q-btn
          no-caps
          color="primary"
          icon="precision_manufacturing"
          :label="$t('StorageManage.ModifyStoragePosture.移动')"
          v-if="!state && step === 3 && !norm.onRobot"
          @click="moveToPosture(calibrationList[0].id)"
        />
        <q-btn
          style="width: 10rem"
          color="primary"
          icon="precision_manufacturing"
          stretch
          @click="
            moveToPosture(mode === '主' ? homeList[0].id : homeList[1].id)
          "
          :label="
            $t('StorageManage.ModifyStoragePosture.移动') +
            (mode === '主' ? ' (主)' : ' (副)')
          "
          v-if="!state && step === 2 && !norm.onRobot"
        >
          <q-btn-dropdown
            flat
            class="absolute-right"
            @click.stop.prevent
            style="right: -2px"
          >
            <q-list>
              <q-item
                clickable
                v-close-popup
                v-for="item in ['主', '副']"
                v-bind:key="item"
                @click="mode = item"
              >
                <q-item-section :class="mode === item ? 'text-blue' : ''">
                  <q-item-label>{{ item }}</q-item-label>
                </q-item-section>
              </q-item>
            </q-list>
          </q-btn-dropdown>
        </q-btn>
        <q-btn
          no-caps
          color="primary"
          icon="precision_manufacturing"
          :label="$t('StorageManage.ModifyStoragePosture.移动')"
          v-if="!state && step === 2 && norm.onRobot"
          @click="moveToPosture(homeList[0].id)"
        />
        <div
          v-if="functionStore.mode === 'remote'"
          class="q-gutter-x-md q-ml-md"
        >
          <q-btn
            label="抓"
            color="deep-orange-5"
            v-if="step === 5"
            @click="grab"
          />
          <q-btn
            label="放"
            color="brown-5"
            v-if="step === 5"
            @click="release"
          />
        </div>
        <!--        <q-icon name="close" size="lg"/>-->
      </q-card-section>
      <q-stepper
        :class="ui.cardClass"
        v-model="step"
        done-color="light-blue-6"
        active-color="light-blue-6"
        error-color="red-5"
        vertical
        header-nav
        animated
      >
        <!--  设置规格   -->
        <q-step
          :name="1"
          :title="$t(lang + '库位规格')"
          :caption="$t(lang + '设置库位的排列层和场景与分组等规格信息')"
          icon="settings"
          :done="step > 1"
          style="width: 30rem"
        >
          <br />
          <div class="q-gutter-y-sm">
            <q-input
              :dark="ui.isDark"
              dense
              outlined
              v-model="norm.name"
              :placeholder="$t(lang + '请输入名称进行后续操作')"
            />
            <div class="row q-gutter-x-sm">
              <q-input
                :dark="ui.isDark"
                class="col"
                dense
                outlined
                v-model="norm.length"
                type="number"
                :label="$t(lang + '长')"
              />
              <q-input
                :dark="ui.isDark"
                class="col"
                dense
                outlined
                v-model="norm.width"
                type="number"
                :label="$t(lang + '宽')"
              />
              <q-input
                :dark="ui.isDark"
                class="col"
                dense
                outlined
                v-model="norm.height"
                type="number"
                :label="$t(lang + '高')"
              />
            </div>
            <q-slide-transition>
              <div
                class="full-width"
                v-if="
                  norm.name &&
                  norm.length > 0 &&
                  norm.width > 0 &&
                  norm.height > 0
                "
              >
                <q-btn
                  no-caps
                  v-if="
                    norm.name &&
                    norm.length > 0 &&
                    norm.width > 0 &&
                    norm.height > 0
                  "
                  class="full-width"
                  @click="step = 2"
                  :class="ui.btnClass"
                  :label="$t(lang + '确认规格信息')"
                  icon="check"
                />
              </div>
            </q-slide-transition>
          </div>
        </q-step>
        <q-step
          :name="2"
          :title="$t(lang + '设置准备点')"
          :caption="$t(lang + '获取准备点')"
          icon="home"
          :done="step > 2"
          style="width: 30rem"
          :header-nav="homeList.length !== 0"
          :error="homeList.length === 0"
        >
          <br />
          <q-btn
            no-caps
            :label="$t(lang + '修改准备点') + (norm.onRobot ? '' : '(主)')"
            @click="modifyPostures.show(homeList[0], norm)"
            class="full-width"
            icon="home"
            :class="ui.btnClass"
            v-if="homeList.length !== 0"
          />
          <q-btn
            no-caps
            :label="$t(lang + '创建准备点') + (norm.onRobot ? '' : '(主)')"
            outline
            @click="addMainPosture('home', norm.onRobot ? '' : '_1')"
            class="full-width"
            icon="home"
            :class="ui.btnClass"
            v-else
          />
          <template v-if="!norm.onRobot && homeList.length !== 0 && !functionStore.isHiddenSecondaryPosition">
            <q-btn
              no-caps
              :label="$t(lang + '修改准备点') + '(副)'"
              @click="modifyPostures.show(homeList[1], norm)"
              class="full-width q-mt-sm text-white bg-primary text-space text-bold"
              icon="home"
              v-if="homeList.length !== 1"
            />
            <q-btn
              no-caps
              :label="$t(lang + '创建准备点') + '(副)'"
              outline
              @click="addMainPosture('home', norm.onRobot ? '' : '_2')"
              class="full-width q-mt-sm text-white bg-primary text-space text-bold"
              icon="home"
              v-else
            />
          </template>
          <q-btn
            no-caps
            :label="$t(lang + '下一步')"
            @click="step = 3"
            color="light-blue-6"
            class="float-right q-mt-lg"
            outline
            v-if="homeList.length !== 0"
          />
        </q-step>
        <q-step
          :name="3"
          :title="$t(lang + '设置自身库序号')"
          :caption="$t(lang + '选择自生库序号')"
          icon="home"
          :done="step > 2"
          style="width: 30rem"
          :header-nav="norm.index !== ''"
          :error="norm.index === ''"
          v-if="norm.onRobot"
        >
          <br />
          <q-select
            dense
            :label="$t(lang + '选择序号')"
            :dark="ui.isDark"
            v-model="norm.index"
            :options="optionsIndex"
            outlined
          />
          <q-btn
            no-caps
            :label="$t(lang + '下一步')"
            @click="step = 4"
            color="light-blue-6"
            class="float-right q-mt-lg"
            outline
            v-if="norm.index"
          />
        </q-step>
        <q-step
          :name="3"
          :title="$t(lang + '设置校准点')"
          :caption="$t(lang + '自动获取校准点的坐标系')"
          icon="add_a_photo"
          :done="step > 3"
          style="width: 30rem"
          :error="calibrationList.length === 0"
          :header-nav="calibrationList.length !== 0"
          v-else
        >
          <br />
          <q-btn
            no-caps
            :label="$t(lang + '修改校准点')"
            @click="modifyPostures.show(calibrationList[0], norm)"
            class="full-width"
            icon="add_a_photo"
            :class="ui.btnClass"
            v-if="calibrationList.length !== 0"
          />
          <q-btn
            no-caps
            :label="$t(lang + '创建校准点')"
            outline
            @click="addMainPosture('calibration')"
            class="full-width"
            icon="add_a_photo"
            :class="ui.btnClass"
            v-else
          />
          <q-btn
            no-caps
            :label="$t(lang + '下一步')"
            @click="step = 4"
            color="light-blue-6"
            class="float-right q-mt-lg"
            outline
            v-if="calibrationList.length !== 0"
          />
        </q-step>
        <q-step
          :name="4"
          :title="$t(lang + '设置过渡点')"
          :caption="
            transitionList.length === 0
              ? $t(lang + '当前未设置过渡点')
              : $t(lang + '当前设置') +
                transitionList.length +
                $t(lang + '个过渡点')
          "
          :error="transitionList.length === 0"
          icon="share"
          :done="step > 4"
          style="width: 30rem"
          :header-nav="
            norm.onRobot ? norm.index !== '' : calibrationList.length !== 0
          "
        >
          <br />
          <div class="row q-gutter-x-sm">
            <q-btn
              no-caps
              rounded
              :class="ui.btnClass"
              :label="$t(lang + '查看过渡点')"
              icon="list"
              @click="normaVisible = true"
              class="col"
            >
              <q-badge color="red" floating>{{
                transitionList.length
              }}</q-badge>
            </q-btn>
            <q-btn
              no-caps
              class="col q-ml-lg"
              rounded
              outline
              color="light-blue-6"
              :label="$t(lang + '新增过渡点')"
              icon="share"
              @click="addMainPosture('transition', transitionList.length)"
            />
          </div>
          <q-btn
            no-caps
            :label="$t(lang + '下一步')"
            @click="step = 5"
            color="light-blue-6"
            class="float-right q-mt-lg"
            outline
          />
        </q-step>
        <!--  设置姿态     -->
        <q-step
          :name="5"
          :title="$t(lang + '设置工位点')"
          :caption="
            referenceList.length === 0
              ? $t(lang + '当前未设置工位点')
              : $t(lang + '当前设置') +
                referenceList.length +
                $t(lang + '个工位点')
          "
          icon="grid_on"
          :error="referenceList.length === 0"
          :done="step > 5"
        >
          <!--          :header-nav="norm.onRobot?norm.index!=='':calibrationList.length!==0"-->

          <div class="q-gutter-y-sm">
            <br />
            <div class="row">
              <template v-for="index of norm.length * norm.width" :key="index">
                <q-btn
                  v-if="occupied.includes(index)"
                  color="secondary"
                  :label="index"
                  class="text-bold"
                  :style="
                    'width: calc(100%/' +
                    norm.width +
                    ');height: calc(100%/' +
                    norm.length +
                    ')'
                  "
                  @click="modifyPosture(index)"
                  style="border-radius: 5px"
                />
                <q-btn
                  v-else
                  :label="index"
                  :color="occupied.includes(index) ? 'secondary' : 'standard'"
                  :outline="!occupied.includes(index)"
                  class="text-weight-bolder"
                  :style="
                    'width: calc(100%/' +
                    norm.width +
                    ');height: calc(100%/' +
                    norm.length +
                    ')'
                  "
                  style="border-radius: 10px"
                  @click="addPosture(index)"
                />
              </template>
            </div>
            <q-btn
              no-caps
              v-if="state"
              :label="$t(lang + '创建库位')"
              :class="ui.btnClass"
              icon="add"
              class="full-width"
              @click="newStorage"
              :disable="btnDisable"
            />
            <!--            <div v-else class="text-right q-gutter-x-sm">-->
            <!--              <q-btn no-caps :label="$t(lang+'保存库位修改')" :class="ui.btnClass" icon="save" @click="modifyStorage"/>-->
            <!--              <q-btn no-caps :label="$t(lang+'还原姿态修改')" color="secondary" icon="sync" @click="getPostureList"/>-->
            <!--            </div>-->
          </div>
        </q-step>
      </q-stepper>
      <div v-if="!state" class="text-right q-gutter-x-sm q-ma-lg">
        <q-btn
          no-caps
          :label="$t(lang + '保存库位修改')"
          :class="ui.btnClass"
          icon="save"
          @click="modifyStorage"
        />
        <q-btn
          no-caps
          :label="$t(lang + '还原姿态修改')"
          color="secondary"
          icon="sync"
          @click="Exit"
        />
      </div>
    </q-card>
  </q-dialog>
  <q-dialog v-model="normaVisible" position="right" seamless>
    <q-card style="min-width: 17vw">
      <q-card-section class="flex items-center q-gutter-x-sm">
        <div class="text-h6">{{ $t(lang + "过渡列表") }}</div>
      </q-card-section>
      <q-list bordered separator>
        <template v-if="transitionList.length !== 0">
          <q-item v-for="(item, index) in transitionList" :key="index">
            <q-item-section>{{ item.name }}</q-item-section>
            <q-item-section side
              ><q-btn
                no-caps
                :label="$t(lang + '查看')"
                color="light-blue-6"
                outline
                @click="modifyPostures.show(item, norm)"
            /></q-item-section>
          </q-item>
        </template>
        <template v-else>
          <q-item>
            <q-item-section class="text-center text-grey">{{
              $t(lang + "暂无过渡点")
            }}</q-item-section>
          </q-item>
        </template>
      </q-list>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import { api } from "boot/axios.js";
import { useAPIStore } from "stores/api";
import { useQuasar } from "quasar";
import { useFunctionsStore } from "stores/functions";
import { status } from "src/utils/deviceWs";
import ModifyStoragePosture from "components/posture/ModifyStoragePosture.vue";
import { useUiStore } from "stores/ui";
import { useI18n } from "vue-i18n";

const t = useI18n().t;
const lang = "StorageManage.ModifyStorage.";
defineExpose({ show });
const emit = defineEmits(["getBank"]);
const props = defineProps({
  // 是否创建自身库
  onRobot: { type: Boolean, default: false },
});
const ui = useUiStore();
const functionStore = useFunctionsStore()
const $q = useQuasar();
const visible = ref(false); // 窗口是否显示
const normaVisible = ref(false); // 过渡点窗口是否显示
const state = ref(true); // 判断是否是修改或添加
const step = ref(1); // 创建规格得进度
const occupied = ref([]); // 包含的坐标
const typeList = ref([]); // 拍照点和准备点list
const referenceList = ref([]); // 参考点List
const homeList = ref([]); // 准备点List
const calibrationList = ref([]); // 拍照点List
const transitionList = ref([]); // 过渡点List
const frameOptions = ref([]); // 所有坐标系
const optionsIndex = ref([]); // 自生库序号
const btnDisable = ref(false);
const mode = ref("主");
const norm = ref({
  // 库位规格
  name: "",
  height: 1,
  width: 1,
  length: 1,
  scenario: "",
  onRobot: false,
  robotId: "",
  index: "",
}); // 规格对象
const modifyPostures = ref();
const newStoragePosture = ref();

// 监听添加页面关闭时是否提示用户告诉数据未保存
watch(visible, (value) => {
  // 判断为添加时
  if (state.value) {
    // 判断在第4个的时候显示列表
    if (step.value === 4) normaVisible.value = value;
    // 判断页面关闭时
    if (!visible.value) {
      // 规格名称未输入不用提醒用户
      if (norm.value.name === "") return;
      $q.dialog({
        dark: ui.isDark,
        title: t(lang + "当前数据还未保存"),
        message: t(lang + "是否要退出退出后所有数据将会失效"),
        html: true,
        cancel: t("cancel"),
        ok: t("ok"),
      })
        .onOk(() => {
          visible.value = false;
        })
        .onCancel(() => {
          visible.value = true;
        });
    }
  } else {
    if (step.value === 4) normaVisible.value = value;
  }
});
// 监听进度条到4时显示过渡列表其他时取消显示
watch(step, (value) => {
  normaVisible.value = value === 4;
});
// 显示规格管理
function show(data, index) {
  // 判断是否是修改姿态
  if (data) {
    step.value = 2;
    norm.value = data;
    getPostureList();
    getFrameList();
    // 赋值库位序号列表
    optionsIndex.value = index;
    optionsIndex.value = [...optionsIndex.value, norm.value.index];
    state.value = false;
  } else {
    // 赋值库位序号列表
    optionsIndex.value = index;
    if (optionsIndex.value.length === 0)
      $q.notify({
        message: t(lang + "自身库已全部创建完成"),
        type: "positive",
        position: "bottom",
      });
    step.value = 1;
    state.value = true;
    // 清空姿态
    norm.value = {
      name: "",
      height: 1,
      width: 1,
      length: 1,
      index: "",
    };
    // 是否添加自身库
    norm.value.onRobot = props.onRobot;
    norm.value.robotId = status.value.device;
    // 清空所有列表
    occupied.value = [];
    typeList.value = [];
    homeList.value = [];
    calibrationList.value = [];
    transitionList.value = [];
    referenceList.value = [];
  }
  visible.value = true;
}
// 获取所有坐标系
function getFrameList() {
  api
    .post(
      useAPIStore().amrUrl + "ros/call",
      {},
      { params: { service: "tf/list_frames" } }
    )
    .then((res) => {
      frameOptions.value = res.data.values.frames;
      // 判断除自身库外进行筛选
      if (!norm.value.onRobot) {
        const isExist =
          frameOptions.value.filter((item) => item === "platform").length === 0;
        if (isExist) {
          $q.dialog({
            dark: ui.isDark,
            title: t(lang + "当前坐标系丢失"),
            message: t(lang + "获取规格内校准坐标系需移动到拍照点进行获取"),
            html: true,
            cancel: t("cancel"),
            ok: t(lang + "获取"),
          }).onOk(() => {
            getCord();
          });
        }
      }
    });
}
// 拍照点获取坐标
function getCord() {
  api
    .post(
      useAPIStore().amrUrl + "ros/call",
      {},
      { params: { service: "/recognize" } }
    )
    .then((res) => {
      if (res.data.values.flag !== 1) {
        $q.dialog({
          dark: ui.isDark,
          title: t(lang + "校准点坐标获取失败"),
          message: t(lang + "检查机械臂摄像头是否对齐拍照点"),
          html: true,
          cancel: t("cancel"),
          ok: t(lang + "重试"),
        })
          .onOk(() => {
            getCord();
          })
          .onCancel(() => {});
      } else {
        $q.notify({
          type: "positive",
          message: t(lang + "坐标获取成功"),
        });
      }
    })
    .catch(() => {
      $q.notify({
        type: "negative",
        message: t(lang + "获取坐标异常"),
      });
    });
}
// 点击按钮创建拍照点坐标系
function creatorCord() {
  $q.dialog({
    dark: ui.isDark,
    title: t(lang + "获取坐标系"),
    message: t(lang + "需机械臂摄像头对齐拍照点"),
    html: true,
    cancel: t("cancel"),
    ok: t("ok"),
  }).onOk(() => {
    getCord();
  });
}
// 获取数据库里的姿态点
function getPostureList() {
  occupied.value = [];
  typeList.value = [];
  homeList.value = [];
  calibrationList.value = [];
  referenceList.value = [];
  transitionList.value = [];
  api
    .get(useAPIStore().postureUrl + "new/posture/storage/" + norm.value.id)
    .then((rs) => {
      if (rs.data.code === 200) {
        referenceList.value = rs.data.data.filter(
          (item) => item.type === "reference"
        );
        typeList.value = rs.data.data.filter(
          (item) => item.type !== "reference"
        );
        homeList.value = rs.data.data.filter((item) => item.type === "home");
        calibrationList.value = rs.data.data.filter(
          (item) => item.type === "calibration"
        );
        transitionList.value = rs.data.data.filter(
          (item) => item.type === "transition"
        );
        referenceList.value.forEach((item) => {
          const nList = item.name
            .replace(norm.value.name, "")
            .replace("-", "")
            .split("_");
          occupied.value.push((nList[0] - 1) * norm.value.width + nList[1] * 1);
        });
        $q.notify({
          message: t(lang + "已加载姿态点数据"),
          type: "positive",
          position: "bottom",
        });
      } else {
        $q.notify({
          message: t(lang + "姿态点数据加载失败"),
          type: "negative",
        });
      }
    })
    .catch(() => {
      $q.notify({
        message: t("RequestError"),
        type: "negative",
      });
    });
}
// 保存对于库位内姿态点的修改
function addAllPosture(id) {
  //  判断是否是空工位
  if (referenceList.value.length !== 0) {
    const data = referenceList.value[0].name;
    const name = data.substring(0, data.lastIndexOf("-"));
    //  保存工位点时规格名称发生改变则会进行判断
    if (name !== norm.value.name) {
      referenceList.value.forEach((item) => {
        item.id =
          norm.value.name +
          "-" +
          item.name.substring(item.name.lastIndexOf("-") + 1, item.name.length);
        item.name =
          norm.value.name +
          "-" +
          item.name.substring(item.name.lastIndexOf("-") + 1, item.name.length);
      });
    }
  }
  const postureList = typeList.value.concat(referenceList.value);
  api
    .put(useAPIStore().postureUrl + "new/posture/" + id, postureList)
    .then((rs) => {
      if (rs.data.code === 200) {
        $q.notify({
          type: "positive",
          message: state.value
            ? t(lang + "库位新增成功")
            : t(lang + "库位修改已保存"),
          position: "bottom",
        });
        state.value = false;
        emit("getBank", norm.value.onRobot);
        visible.value = false;
      } else {
        $q.notify({
          type: "negative",
          message: state.value
            ? t(lang + "库位新增失败")
            : t(lang + "库位保存失败"),
          position: "bottom",
        });
      }
    })
    .catch(() => {
      $q.notify({
        message: t("RequestError"),
        type: "negative",
      });
    });
}
// 保存规格
function newStorage() {
  btnDisable.value = true;
  norm.value.scenario = functionStore.scene.id;
  $q.dialog({
    dark: ui.isDark,
    persistent: true,
    title: t(lang + "规格配置已完成"),
    message: t(lang + "是否要保存库位规格"),
    cancel: t("cancel"),
    ok: t("ok"),
  })
    .onOk(() => {
      api
        .post(useAPIStore().postureUrl + "new/storage", norm.value)
        .then((rs) => {
          if (rs.data.code === 200) {
            addAllPosture(rs.data.data.id);
            btnDisable.value = false;
          } else {
            $q.notify({
              message: t(lang + "规格添加失败姿态将无法添加"),
              type: "negative",
            });
            btnDisable.value = false;
          }
        })
        .catch(() => {
          $q.notify({
            message: t("RequestError"),
            type: "negative",
          });
          btnDisable.value = false;
        });
    })
    .onCancel(() => {
      btnDisable.value = false;
    });
}
// 修改规格
function modifyStorage() {
  $q.dialog({
    dark: ui.isDark,
    title: t(lang + "库位姿态修改"),
    message: t(lang + "是否要保存对库位的修改"),
    cancel: t("cancel"),
    ok: t("ok"),
    persistent: true,
  }).onOk(() => {
    api
      .put(useAPIStore().postureUrl + "new/storage", norm.value)
      .then((rs) => {
        if (rs.data.code === 200) {
          addAllPosture(norm.value.id);
        } else {
          $q.notify({
            message: t(lang + "规格修改失败姿态将无法修改"),
            type: "negative",
          });
        }
      })
      .catch(() => {
        $q.notify({
          message: t("RequestError"),
          type: "negative",
        });
      });
  });
}
// 修改对应坐标下的端点姿态信息
function modifyPosture(index) {
  referenceList.value.forEach((item, i) => {
    // 算出他的下标判断
    const nList = item.name
      .replace(norm.value.name, "")
      .replace("-", "")
      .split("_");
    // 等于点击的下标需要修改姿态坐标
    if ((nList[0] - 1) * norm.value.width + nList[1] * 1 === index) {
      modifyPostures.value.show(referenceList.value[i], norm.value);
    }
  });
}

// 设置端点中的信息
function addPosture(index) {
  // 计算出规格名字
  const a = Math.floor(index / norm.value.width);
  const b = index - a * norm.value.width;
  let x, y;
  if (b === 0) {
    x = a;
    y = norm.value.width;
  } else {
    x = a + 1;
    y = b;
  }
  $q.dialog({
    dark: ui.isDark,
    title: t(lang + "设置工位") + index,
    message: t(lang + "设置该位置为工位"),
    cancel: t("cancel"),
    ok: t("ok"),
  }).onOk(() => {
    const endpoint = {};
    endpoint.name =
      norm.value.name + "-" + x + "_" + y + "_" + norm.value.height;
    endpoint.id = norm.value.name + "-" + x + "_" + y + "_" + norm.value.height;
    endpoint.type = "reference";

    occupied.value.push(index);
    referenceList.value.push(endpoint);
    newStoragePosture.value.show(endpoint, norm.value);
  });
}

// 删除姿态点
function removePosture(posture) {
  if (typeList.value.lastIndexOf(posture) !== -1) {
    const index = typeList.value.lastIndexOf(posture);
    typeList.value.splice(index, 1);
    homeList.value = typeList.value.filter((item) => item.type === "home");
    calibrationList.value = typeList.value.filter(
      (item) => item.type === "calibration"
    );
    transitionList.value = typeList.value.filter(
      (item) => item.type === "transition"
    );
    $q.notify({
      message: t(lang + "基准姿态点") + posture.name + t(lang + "删除成功"),
      type: "positive",
      position: "bottom",
    });
    return;
  }
  if (referenceList.value.lastIndexOf(posture) !== -1) {
    const index = referenceList.value.lastIndexOf(posture);
    referenceList.value.splice(index, 1);
    occupied.value.splice(index, 1);
    $q.notify({
      message: t(lang + "姿态点") + posture.name + t(lang + "删除成功"),
      type: "positive",
      position: "bottom",
    });
  }
}

// 缓存添加规格里的home点和过渡点和拍照点
function addMainPosture(type, index) {
  const endpoint = {};
  endpoint.type = type;
  typeList.value.push(endpoint);
  homeList.value = typeList.value.filter((item) => item.type === "home");
  calibrationList.value = typeList.value.filter(
    (item) => item.type === "calibration"
  );
  transitionList.value = typeList.value.filter(
    (item) => item.type === "transition"
  );
  newStoragePosture.value.show(endpoint, norm.value, index);
}
// 当前姿态移动
function moveToPosture(id) {
  $q.dialog({
    title: "移动",
    message: "请选择移动类型",
    options: {
      type: "radio",
      model: "joint",
      // inline: true
      items: [
        { label: "关节", value: "joint" },
        { label: "直线", value: "linear" },
      ],
    },
    cancel: t("cancel"),
    ok: t("ok"),
    persistent: true,
  }).onOk((data) => {
    api
      .get(useAPIStore().amrUrl + "amr/add", {
        params: { type: "posture", content: id + "," + data },
      })
      .then((rs) => {
        if (rs.data === "done") {
          $q.notify({
            type: "positive",
            message: t(lang + "指令已下发"),
            position: "bottom",
          });
        }
      })
      .catch(() => {
        $q.notify({
          type: "negative",
          message: t(lang + "接口调用出现错误"),
          position: "bottom",
        });
      });
  });
}
function Exit() {
  $q.dialog({
    dark: ui.isDark,
    title: t(lang + "提示"),
    message: t(lang + "是否重置姿态并退出修改"),
    cancel: t("cancel"),
    ok: t("ok"),
  }).onOk(() => {
    visible.value = false;
  });
}
// 调试操作库和自身库抓取
function grab() {
  $q.dialog({
    title: "测试抓工件",
    message: "选择需要测试的夹具进行测试！",
    options: {
      type: "radio",
      model: "flange",
      items: [
        { label: "左夹具", value: "flange" },
        { label: "右夹具", value: "flange" },
      ],
    },
    cancel: true,
    persistent: true,
  }).onOk((data) => {
    moveCatch(getRosPose(data, "catch"), norm.value.onRobot);
  });
}
// 调试操作库和自身库放
function release() {
  $q.dialog({
    title: "测试放工件",
    message: "选择需要测试的夹具进行测试！",
    options: {
      type: "radio",
      model: "flange",
      items: [
        { label: "左夹具", value: "flange" },
        { label: "右夹具", value: "flange" },
      ],
    },
    cancel: true,
    persistent: true,
  }).onOk((data) => {
    moveCatch(getRosPose(data, "put"), norm.value.onRobot);
  });
}
function getRosPose(data, type) {
  const pose = {
    pose: {
      header: { seq: 1, stamp: { nsec: 0, sec: 0 }, frame_id: "" },
      pose: {
        orientation: {
          x: "",
          y: "",
          z: "",
          w: "",
        },
        position: {
          x: "",
          y: "",
          z: "",
        },
      },
    },
    tool: "",
    action: "",
  };
  pose.tool = data;
  pose.action = type;
  pose.pose.pose.orientation.x = referenceList.value[0].qx;
  pose.pose.pose.orientation.y = referenceList.value[0].qy;
  pose.pose.pose.orientation.z = referenceList.value[0].qz;
  pose.pose.pose.orientation.w = referenceList.value[0].qw;
  pose.pose.pose.position.x = referenceList.value[0].x;
  pose.pose.pose.position.y = referenceList.value[0].y;
  pose.pose.pose.position.z = referenceList.value[0].z;
  pose.pose.header.frame_id = referenceList.value[0].frameID;

  return pose;
}

function moveCatch(data, type) {
  api
    .post(useAPIStore().amrUrl + "ros/call", data, {
      params: { service: "/move_catch" },
    })
    .then((res) => {
      if (res.data.values.result === "SUCCEED") {
        if (data.action === "put") {
          if (type) {
            $q.notify({
              type: "positive",
              message:
                data.tool === "flange"
                  ? "左夹具去自生库放工件,指令下发成功！"
                  : "右夹具去自生库放工件,指令下发成功！",
              position: "bottom",
            });
          } else {
            $q.notify({
              type: "positive",
              message:
                data.tool === "flange"
                  ? "左夹具去机床库放工件,指令下发成功！"
                  : "右夹具去机床库放工件,指令下发成功！",
              position: "bottom",
            });
          }
        } else {
          if (type) {
            $q.notify({
              type: "positive",
              message:
                data.tool === "flange"
                  ? "左夹具去自生库抓工件,指令下发成功！"
                  : "右夹具去自生库抓工件,指令下发成功！",
              position: "bottom",
            });
          } else {
            $q.notify({
              type: "positive",
              message:
                data.tool === "flange"
                  ? "左夹具去机床库抓工件,指令下发成功！"
                  : "右夹具去机床库抓工件,指令下发成功！",
              position: "bottom",
            });
          }
        }
      } else {
        $q.notify({
          message: "指令下发失败！",
          type: "negative",
        });
      }
    })
    .catch(() => {
      $q.notify({
        message: t("RequestError"),
        type: "negative",
      });
    });
}
</script>
